package com.maruping.disk.user.control;

import com.maruping.disk.mybatis.entity.PtUserEntity;
import com.maruping.disk.spring.security.GdmtPasswordEncoder;
import com.maruping.disk.user.exception.EmailRepeatException;
import com.maruping.disk.user.exception.MobileRepeatException;
import com.maruping.disk.user.exception.UserNameRepeatException;
import com.maruping.disk.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

public class ChangePasswordController {
    @Autowired
    private UserService userService;

    @Autowired
    private GdmtPasswordEncoder passwordEncoder;

    @GetMapping("/changePassword")
    public String showChangePasswordPage(Model model) {
        model.addAttribute("user", new PtUserEntity());
        return "user/changePassword";
    }

    @PostMapping("/changePassword")
    public String changePassword(PtUserEntity userEntity) throws UserNameRepeatException, MobileRepeatException, EmailRepeatException {
        // 获取当前用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        PtUserEntity currentUser = userService.queryUserInfoByName(username);

        // 编码新密码并更新
        String encodedPassword = passwordEncoder.encode(userEntity.getPassword());
        currentUser.setPassword(encodedPassword);
        userService.modifyUserInfoById(currentUser);

        return "redirect:/login/login"; // 修改后重定向到登录页
    }
}
